package com.sky.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.dto.CreateAddressDTO;
import com.sky.dto.UpdateAddressDTO;
import com.sky.entity.Address;
import com.sky.mapper.AddressMapper;
import com.sky.service.AddressService;
import com.sky.vo.AddressVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService {
    @Override
    public List<AddressVO> getAddressList(Long studentId) {
        List<Address> addresses = baseMapper.selectByStudentId(studentId);
        return addresses.stream()
                .map(address -> {
                    AddressVO addressVO = new AddressVO();
                    BeanUtils.copyProperties(address, addressVO);
                    return addressVO;
                })
                .collect(Collectors.toList());
    }

    @Override
    public AddressVO getAddressById(Long id) {
        Address address = baseMapper.selectById(id);
        if (address == null) {
            return null;
        }
        AddressVO addressVO = new AddressVO();
        BeanUtils.copyProperties(address, addressVO);
        return addressVO;
    }

    @Override
    public Long createAddress(CreateAddressDTO createAddressDTO) {
        Address address = new Address();
        BeanUtils.copyProperties(createAddressDTO, address);
        baseMapper.insert(address);
        // 如果设置为默认地址，需要取消其他地址的默认状态
        if (Boolean.TRUE.equals(address.getIsDefault())) {
            setDefaultAddress(address.getId());
        }
        return address.getId();
    }

    @Override
    public void updateAddress(UpdateAddressDTO updateAddressDTO) {
        Address address = new Address();
        BeanUtils.copyProperties(updateAddressDTO, address);
        baseMapper.updateById(address);
        // 如果设置为默认地址，需要取消其他地址的默认状态
        if (Boolean.TRUE.equals(address.getIsDefault())) {
            setDefaultAddress(address.getId());
        }
    }

    @Override
    public void deleteAddress(Long id) {
        baseMapper.deleteById(id);
    }

    @Transactional
    @Override
    public void setDefaultAddress(Long id) {
        Address address = baseMapper.selectById(id);
        if (address != null) {
            // 取消其他地址的默认状态
            baseMapper.cancelOtherDefaultAddresses(address.getStudentId(), id);
            // 设置当前地址为默认地址
            baseMapper.setDefaultAddress(id);
        }
    }
}